#!/usr/bin/env bash

#error info:
#[6794385.273969] XFS (sde3): Filesystem has duplicate UUID fb1a2304-2f9d-4af0-9d59-2cd0afe2fecd - can't mount
#
#fixed method:
#1. sudo mount -o rw,nouuid /dev/sde3 ~/book
#
##need -o rw,nouuid every time after rebook system, now you can use xfs_admin to regenerate the uuid for /dev/sde3
##xfs_admin need umount the /dev/sde3 firstly
#2. sudo umount /dev/sde3
#3. sudo xfs_admin -U generate /dev/sde3

#get this script real directory
SOURCE="$0"
while [ -h "$SOURCE"  ]; do # resolve $SOURCE until the file is no longer a symlink
    this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"
    SOURCE="$(readlink "$SOURCE")"
    # if $SOURCE was a relative symlink, 
    #we need to resolve it relative to the path 
    #where the symlink file was located
    [[ $SOURCE != /*  ]] && SOURCE="$this_script_dir/$SOURCE"
done
this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"

log_level=${log_level:=info}
assist_dir=${assist_dir:=$this_script_dir/assist}
source $assist_dir/global.sh
################################################################################
#                                                                          80col
print_help()
{
    cat <<EOF
    useage:
    fix duplicate uuid: $0 --uuid --dev=/dev/sde3
                        $0 --list

    --dev=/dev/sde3
    --uuid                 - fix xfs uuid problemd, result in mount /dev failed.

    --list                 - show all device , by execute: sudo fdisk -l

    --log_level=<debug> - control pint log on streen,trace|debug|info|warn|error|critical

    --help  - prints help screen, script will exit after printing


EOF
}
sudo mount -o rw,nouuid /dev/sde3 ~/book


fix_uuid()
{
    local device=$dev
    sudo mount -o rw,nouuid $device ~/book
    sleep 3

    if sudo umount $device ; then
        sudo xfs_admin -U generate $device

        vlogi "remount $device to ~/book"
        sudo mount $device ~/book
    else
        vloge "umount $device failed"
    fi
}

main()
{
    if [ $_arg_num_ -eq 0 ] || [ -n "$help" ] ; then
        print_help
        exit 0;
    fi

    if [ -n "$uuid" ] ; then
        check_argument dev || exit 1

        fix_uuid
    elif [ -n "$list" ] ; then
        sudo fdisk -l
    fi

    return 0
}

main && exit 0 || exit 1


